package org.linlinjava.litemall.wx.web;

import org.linlinjava.litemall.core.util.DateTimeUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.LitemallOrderGoodsService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.service.LitemallSpellService;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.WxSpellService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wx/spell")
@Validated
public class WxSpellController {

    @Autowired
    private WxSpellService wxSpellService;

    @Autowired
    private LitemallSpellService spellService;

    @Autowired
    private LitemallOrderGoodsService orderGoodsService;

    @Autowired
    private LitemallOrderService orderService;

    /**
     * 发起拼单, 并获取详情
     *
     * @param userId  用户ID
     * @param orderId 订单ID
     * @return
     */
    @GetMapping("open")
    public Object open(@LoginUser Integer userId, @NotNull Integer orderId) {
        HashMap<String, Object> result = new HashMap<>();
        // 查询拼单发起
        LitemallSpell spell = spellService.queryInitiatorByOrderId(orderId);
        if (spell == null) {
            ResponseUtil.fail(400, "该单尚未出现拼单记录，出现错误");
//            LitemallOrderGoods goods = orderGoodsService.queryOneGoodsByOid(orderId);
//            if (goods == null) {
//                ResponseUtil.fail(400, "该单存在多商品无法拼单");
//            }
//            spell = wxSpellService.open(userId, orderId, goods.getGoodsId());
        }

        return wxSpellService.detail(userId, spell.getId());
    }

    /**
     * 获取拼单详情
     *
     * @param userId
     * @param id
     * @return
     */
    @GetMapping("detail")
    public Object detail(@LoginUser Integer userId, @NotNull Integer id, String type) {
        if ("join".equals(type)) {
            LitemallSpell spell = spellService.queryJoinRecord(id);
            return wxSpellService.detail(userId, spell.getId());
        }
        return wxSpellService.detail(userId, id);
    }

    /**
     * 用户开拼或入拼情况
     *
     * @param userId   用户ID
     * @param showType 显示类型，如果是0，则是当前用户开的拼单；否则，则是当前用户参加的拼单
     * @return 用户开拼或入拼情况
     */
    @GetMapping("my")
    public Object my(@LoginUser Integer userId,
                     @RequestParam(defaultValue = "0") Integer showType,
                     @RequestParam(defaultValue = "1") Integer page,
                     @RequestParam(defaultValue = "10") Integer limit,
                     @Sort @RequestParam(defaultValue = "add_time") String sort,
                     @Order @RequestParam(defaultValue = "desc") String order) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        List<LitemallSpell> spells;
        if (showType == 0) {
            spells = spellService.queryStartSpell(userId, page, limit, sort,
                    order);
        } else {
            spells = spellService.queryJoinSpell(userId, page, limit, sort,
                    order);
        }
        List<Map<String, Object>> spellVoList = new ArrayList<>(spells.size());
        for (LitemallSpell spell : spells) {
            HashMap<String, Object> spellVo = new HashMap<>();
            spellVo.put("id", spell.getId());
            spellVo.put("reducePrice", spell.getReducePrice());
            spellVo.put("status", spell.getStatus());
            LitemallOrder orderVo = orderService.findById(spell.getOrderId());
            spellVo.put("allGoodsPrice", orderVo.getGoodsPrice());
            spellVo.put("freightPrice", orderVo.getFreightPrice());
            spellVo.put("actualPrice", orderVo.getActualPrice());
            LitemallOrderGoods orderGoods = orderGoodsService.queryOneGoodsByOid(spell.getOrderId());
            spellVo.put("goodsId", orderGoods.getGoodsId());
            spellVo.put("goodsName", orderGoods.getGoodsName());
            spellVo.put("goodsPrice", orderGoods.getPrice());
            spellVo.put("goodsNumber", orderGoods.getNumber());
            spellVo.put("specifications", orderGoods.getSpecifications());
            spellVo.put("goodsPic", orderGoods.getPicUrl());
            spellVo.put("orderId", spell.getOrderId());
            spellVo.put("leftTime", DateTimeUtil.leftTime(spell.getExpireTime()));
            spellVoList.add(spellVo);
        }
        return ResponseUtil.okList(spellVoList);
    }

}
